package com.example.picturebacked.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.picturebacked.api.aliyunai.AliYunAiApi;
import com.example.picturebacked.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.example.picturebacked.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.example.picturebacked.exception.BusinessException;
import com.example.picturebacked.exception.ErrorCode;
import com.example.picturebacked.exception.ThrowUtils;
import com.example.picturebacked.manager.CosManager;
import com.example.picturebacked.manager.FileManager;
import com.example.picturebacked.manager.upload.FilePictureUpload;
import com.example.picturebacked.manager.upload.PictureUploadTemplate;
import com.example.picturebacked.manager.upload.URLPictureUpload;
import com.example.picturebacked.model.dto.file.UploadPictureResult;
import com.example.picturebacked.model.dto.picture.*;
import com.example.picturebacked.model.entity.Picture;
import com.example.picturebacked.model.entity.Space;
import com.example.picturebacked.model.entity.User;
import com.example.picturebacked.model.enums.PictureReviewStatusEnum;
import com.example.picturebacked.model.vo.PictureVO;
import com.example.picturebacked.model.vo.UserVO;
import com.example.picturebacked.service.PictureService;
import com.example.picturebacked.mapper.PictureMapper;
import com.example.picturebacked.service.SpaceService;
import com.example.picturebacked.service.UserService;
import com.example.picturebacked.utils.ColorSimilarUtils;
import com.example.picturebacked.utils.ColorTransformUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lbt
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-08-20 14:56:26
 */
@Slf4j
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    @Resource
    private FileManager fileManager;

    @Resource
    private CosManager cosManager;

    @Resource
    private UserService userService;

    @Resource
    private FilePictureUpload filePlictureupload;

    @Resource
    private URLPictureUpload urlPictureUpload;

    @Resource
    private SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;

    /**
     * 用户图片上传
     *
     * @param inputSource          文件上传的源地址（本地或者URL）
     * @param pictureUploadRequest 上传图片的请求
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User userLogin) {
        /**
         * 整体逻辑
         *      1. 判断用户是否登录
         *      2. 通过传递过来的请求id是否存在，判断是新增图片还是更新图片
         *          如果传入的请求id为空，则表示新增图片
         *          不管添加还是更新，都进行图片上传，将前端传递的multipartFile文件通过用户名id进行区分上传保存
         *      3. 保存图片信息到数据库，进行区分是更新还是新增
         *          判断pictureId是否为空
         *              为空则表示新增图片
         *              不为空表示更新图片
         *      4. 通过使用saveOrUpdate方法进行自动判断是更新还是新增
         *      5. 返回图片信息
         */
        if (inputSource == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片为空");
        }
        // 校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            // 需要上传到私人空间中
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 必须空间创建人才能上传
            if (!space.getUserId().equals(userLogin.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            // 检验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间大小不足");
            }
        }
        // 校验是否有空间的权限
        // 判断用户是否登录
        ThrowUtils.throwIf(userLogin == null, ErrorCode.NO_AUTH_ERROR);
        // 判断新增还是删除
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            // 更新
            pictureId = pictureUploadRequest.getId();
        }
        // 如果是更新，判断图片是否为空
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 仅本人或者管理员才能编辑
            if (!oldPicture.getUserId().equals(userLogin.getId()) && !userService.isAdmin(userLogin)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }

            // 校验空间是否一致
            // 没传 spaceId，则直接复用原有图片的spaceId
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传递了spaceId，必须与原图一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间不一致");
                }
            }

        }

        // 根据每个用户进行上传图片分类  => 按照空间划分目录
        String uploadPathPrefix;
        if (spaceId == null) {
            uploadPathPrefix = String.format("public/%s", userLogin.getId());
        } else {
            uploadPathPrefix = String.format("space/%s", spaceId);
        }
        // 上传图片并获取返回的图片信息
        // 通过先确认图片上传方式，然后使用模板模式进行上传
        PictureUploadTemplate pictureUploadTemplate = filePlictureupload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        // 使用 Picture 进行保存到数据库
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setSpaceId(spaceId);
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        // 转换为标准颜色
        picture.setPicColor(ColorTransformUtils.getStandardColor(uploadPictureResult.getPicColor()));
        picture.setUserId(userLogin.getId());
        // 补充审核参数
        fillReviewParams(picture, userLogin);

        // 如果pictureId不为空，表示更新，否则是新增
        if (pictureId != null) {
            // 更新，需要补充id，使数据库知道是哪个数据进行的更新
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 使用saveOrUpdate方法进行自动判断是更新还是新增
        // 上传完成后更新空间额度，同时更新空间的大小以及数量
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "空间额度更新失败");
            }
            return picture;
        });


        return PictureVO.objToVo(picture);
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapepr(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        long current = pictureQueryRequest.getCurrent();
        long pageSize = pictureQueryRequest.getPageSize();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 获取请求编辑时间参数
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        // 如果搜索条件不为空，则在图片名称字段和图片简介字段进行模糊查询
        if (StrUtil.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText));
        }
        // 如果说搜索条件为空，则使用传递过来的图片参数进行查询
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewMessage), "reviewMessage", reviewMessage);
        // 大于等于startEditTime 小于endEditTime
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);

        queryWrapper.isNull(nullSpaceId, "spaceId");
        // 将编辑时间加入到查询条件中
        // 因为tags是数组，所以需要单个进行拼接查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 获取对图片封装的方法，将原有的图片关联创建用户的信息
     *
     * @param picture
     * @param request
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 先将图片对象 转为 返回类型的图片对象
        PictureVO pictureVO = PictureVO.objToVo(picture);

        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUserVO(userVO);
        }
        return pictureVO;
    }

    /**
     * 将获取到的图片转换为PictureVO对象
     * 传入查询到的图片分页信息（将原始的Picture传入到内容中，并转换为PictureVO对象）
     *
     * @param picturePage
     * @param request
     * @return
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        // 得到查询到的图片信息
        List<Picture> pictureList = picturePage.getRecords();
        // 创建一个图片分页对象   getCurrent当前页  getSize获取每页显示的条数     getTotal获取数据总数
        // 创建一个分页pictureVO对象，复制当前页数、每页显示的条数、总条数
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(),
                picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }

        // 将数组中Picture 对象转为PictureVO对象
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 将传入的图片信息的用户ID进行去重获取
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());

        // 根据用户ID进行分组 最后的结果是 用户id 用户信息
        // 为什么返回的是List<User>而不是User是因为，流式操作时，哪怕最后返回的是一个对象，那么返回的还是List<User>
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet)
                .stream().collect(Collectors.groupingBy(User::getId));
        // 填充信息，将用户信息填充到pictureVO对象中
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            // 判断用户ID是否在userIdUserListMap中，使用Map的key进行对比
            if (userIdUserListMap.containsKey(userId)) {
                // 如果对比成功，则取出第一个map中第一个用户的信息
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUserVO(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);

        return pictureVOPage;
    }

    /**
     * 图片参数校验，在修改/更新操作时用于判断参数是否合法
     *
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 进行判断
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url长度不能超过1024");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介长度过长");
        }
    }

    /**
     * 图片审核，只设置审核人以及状态
     *
     * @param pictureReviewRequest
     * @param userLogin
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User userLogin) {
        Long id = pictureReviewRequest.getId();
        // 获取状态
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        // 获取枚举中的状态
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Picture oldPicture = this.getById(id);
        if (oldPicture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请勿重复审核");
        }
        // 更新审核状态
        Picture picture = new Picture();
        BeanUtil.copyProperties(pictureReviewRequest, picture);
        picture.setReviewerId(userLogin.getId());
        picture.setReviewTime(new Date());
        boolean b = this.updateById(picture);
        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
            picture.setReviewMessage("管理员自动过审");
        } else {
            // 非管理员，创建或者编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User userLogin) {
        // 获取请求参数（搜索词、搜索数量）
        String searchText = pictureUploadByBatchRequest.getSearchText();
        Integer count = pictureUploadByBatchRequest.getCount();
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)) {
            namePrefix = searchText;
        }
        if (count > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "搜索数量不能超过30");
        }
        // 要抓取的地址
        String fetchUrl = String.format("https://www.bing.com/images/async?q=%s&mmasync=1&cc=cn", searchText);
        // 获取返回的图片信息
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取图片信息失败：{}", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取页面信息失败");
        }
        // 获取图片的内容
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取元素失败");
        }
        // 获取img.mimg修饰的图片信息
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            // 获取图片地址
            String fileURL = imgElement.attr("src");
            if (StrUtil.isBlank(fileURL)) {
                log.info("图片地址为空：{}", fileURL);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileURL.indexOf("?");
            // 清除中间参数
            if (questionMarkIndex > -1) {
                fileURL = fileURL.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setFileUrl(fileURL);
            pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
            try {
                PictureVO pictureVO = this.uploadPicture(fileURL, pictureUploadRequest, userLogin);
                log.info("图片上传成功：{}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败：{}", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    /**
     * 开启异步删除
     *
     * @param oldPicture 传入要删除的对象
     */
    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        String pictureUrl = oldPicture.getUrl();
        // 判断有多条记录引用了该URL
        Long count = this.lambdaQuery().eq(Picture::getUrl, pictureUrl).count();
        if (count > 1) {
            // 如果有多条记录引用该URL，则不删除
            return;
        }
        // 如果等于1
        cosManager.deleteObject(pictureUrl);
        // 同时清理缩略图
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if (StrUtil.isNotBlank(thumbnailUrl)) {
            cosManager.deleteObject(thumbnailUrl);
        }
    }

    @Override
    public void checkPictureAuth(Picture picture, User userLogin) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            //  公共图库，只允许本人或者管理员才能操作
            if (!picture.getUserId().equals(userLogin.getId()) && !userService.isAdmin(userLogin)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }

        } else {
            // 私有空间只有空间管理员才能操作
            if (!picture.getUserId().equals(userLogin.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    @Override
    public void deletePicture(Long pictureId, User userLogin) {
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(userLogin == null, ErrorCode.NO_AUTH_ERROR);
        // 判断是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
//        checkPictureAuth(oldPicture, userLogin);


        // 删除文件后，更新空间额度
        transactionTemplate.execute(status -> {
            // 删除图片
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                // 更新空间额度
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, oldPicture.getSpaceId())
                        .setSql("totalSize = totalSize -" + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount -1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 清除对象存储中的文件
        this.clearPictureFile(oldPicture);
    }

    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User userLogin) {
        Picture picture = new Picture();
        BeanUtil.copyProperties(pictureEditRequest, picture);
        // 将tags 的List 转为String
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 更新编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 判断是否存在
        Long id = pictureEditRequest.getId();
        Picture editPicture = this.getById(id);
        ThrowUtils.throwIf(editPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员才能编辑 -> 校验权限
//        this.checkPictureAuth(editPicture, userLogin);
        this.fillReviewParams(picture, userLogin);
        boolean b = this.updateById(picture);
        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);

    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String pictureColor, User loginUser) {
        // 1.校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(pictureColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2.校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        // 3.查询该空间下所有图片（必须有主色调）
        // 获取图片中空间id与当前空间id相同并且图片中有主色调的图片
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果图片列表为空直接返回空数组
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 4.计算相似度并排序
        // 将想要获取的图片颜色转为Color对象，就可以直接使用图片工具类中Color之间对比而不用将HexColor再转为Color进行对比，减少了方法的调用
        Color targetColor = Color.decode(pictureColor);
        List<Picture> sortedPictures = pictureList.stream()
                // 对比每个查询到的图片列表与目标颜色对比
                .sorted(Comparator.comparingDouble((picture -> {
                    // 提取列表中每个图片的主色调
                    String hexColor = picture.getPicColor();
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    // 转化为Color对象
                    Color picColor = Color.decode(hexColor);
                    // 越大越相似，但是在list中越大就会越靠后
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, picColor);
                })))
                // 获取前12张相似度最高的图片
                .limit(12)
                .collect(Collectors.toList());
        // 5.返回结果, 将图片列表转为VO
        return sortedPictures.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User userLogin) {
        // 判断是否合法
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        String nameRule = pictureEditByBatchRequest.getNameRule();

        ThrowUtils.throwIf(spaceId == null || CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(userLogin == null, ErrorCode.NO_AUTH_ERROR);

        // 检验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(userLogin.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        // 查询指定图片，仅选择需要的字段
        // 查询图片的id和空间id，判断图片查询到的图片中和当前空间id一致，并且图片id与传入要修改的id列表中一致的图片
        List<Picture> pictureList = this.lambdaQuery().select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        if (pictureList.isEmpty()) {
            return;
        }
        // 更新分类和标签
        pictureList.forEach(picture -> {
            // 只有当传入的标签和分类有值时才更改，否则不修改
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        // 批量重命名
        fillPictureWithNameRule(pictureList, nameRule);

        // 使用批量修改数据，快速更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * 创建AI扩图任务
     *
     * @param createPictureOutPaintingTaskRequest 扩图任务请求
     * @param userLogin                           登录用户
     * @return
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User userLogin) {
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        // 判断图片是否为空，为空则直接抛出异常
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验
//        checkPictureAuth(picture, userLogin);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

    /**
     * 修改的命名规则
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (StrUtil.isBlank(nameRule) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }

}




























